package com.suncnpap.statistics.controller;

import com.github.pagehelper.PageInfo;
import com.suncnpap.library.model.*;
import com.suncnpap.library.service.BookLossService;
import com.suncnpap.library.service.BookshelfService;
import com.suncnpap.library.service.BorrowBookRecordService;
import com.suncnpap.library.service.BorrowBookService;
import com.suncnpap.library.service.ChineseClassificationService;
import com.suncnpap.library.service.CollectionChangeService;
import com.suncnpap.library.service.LibraryService;
import com.suncnpap.library.service.ReturnBookService;

import com.suncnpap.reader.service.ReaderService;
import com.suncnpap.reader.service.ReaderTypeService;
import com.suncnpap.statistics.model.LatelyVo;
import com.suncnpap.system.model.School;
import com.suncnpap.system.service.ConfigService;
import com.suncnpap.system.service.SchoolService;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.suncnpap.system.service.TNoticeNoticeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.app.util.common.HandlerResult;
import com.app.util.common.ObjUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryField;
import com.app.util.database.mybatis.QueryLinkType;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.controller.BaseController;

/** 
 * 说明：书库Controller
 */
@Api(description = "首页")
@Controller
@RequestMapping(value="/search")
public class SearchController extends BaseController {
	
	//private static final Logger log = Logger.getLogger(LibraryController.class);
	
	@Autowired
	LibraryService libraryService;
	
	@Autowired
	BorrowBookService borrowBookService;
	
	@Autowired
	BorrowBookRecordService borrowBookRecordService;
	
	@Autowired
	ReturnBookService returnBookService;
	
	@Autowired
	ReaderTypeService readerTypeService;
	
	@Autowired
	ReaderService readerService;
	
	@Autowired
	CollectionChangeService collectionChangeService;
	
	@Autowired
	BookLossService bookLossService;
	
	@Autowired
	ChineseClassificationService chineseClassificationService;
	
	@Autowired
	ConfigService configService;
	
	@Autowired
	SchoolService schoolService;
	
	@Autowired
	BookshelfService bookshelfService;
	/**
	 * 去往列表页面
	 * @param
	 * @return
	 */
//	@ApiOperation("首页检索")

	@RequestMapping(value="/list")
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		

		Page page = this.setPage();
		
		String keyName = this.getParameter("keyName", "");
		String keywords = this.getParameter("keywords", "");
		page.setKeyName(keyName);
		page.setKeywords(keywords);
//		if(!keyName.equals("")){
//			page.addQueryAnd(keyName, QueryType.markLIKE, keywords);
//		}
		
		//正题名
		String strPositiveTitle = this.getParameter("strPositiveTitle","");	//正题名
		if(!"".equals(strPositiveTitle)){
			page.addQueryAnd("strPositiveTitle", QueryType.markLIKE, strPositiveTitle);
		}
		
		//责任人
		String strFirstResponsible = this.getParameter("strFirstResponsible", "");
		if(!strFirstResponsible.equals("")){
			page.addQueryAnd("strFirstResponsible", QueryType.markLIKE, strFirstResponsible);
		}
		
		//ISBN
		String strISBN = this.getParameter("strISBN","");
		if(!"".equals(strISBN)){
			page.addQueryAnd("strISBN", QueryType.markLIKE, strISBN);
		}
		
		//分类号
		String strClassNumber = this.getParameter("strClassNumber", "");
		if(!strClassNumber.equals("")){
			page.addQueryAnd("strClassNumber", QueryType.markLIKE, strClassNumber);
		}
		
		//出版地
		String strPublisherPlace = this.getParameter("strPublisherPlace", "");
		if(!strPublisherPlace.equals("")){
			page.addQueryAnd("strPublisherPlace", QueryType.markLIKE, strPublisherPlace);
		}
		
		//出版社
		String strPublisher = this.getParameter("strPublisher", "");
		if(!strPublisher.equals("")){
			page.addQueryAnd("strPublisher", QueryType.markLIKE, strPublisher);
		}
		
		//年份
		String strStartYear = this.getParameter("strStartYear", "");
		if(!strStartYear.equals("")){
			page.addQueryAnd("year(strPublicationDate)", QueryType.markGTEQ, strStartYear);
		}
		
		String strEndYear = this.getParameter("strEndYear", "");
		if(!strEndYear.equals("")){
			page.addQueryAnd("year(strPublicationDate)", QueryType.markLTEQ, strEndYear);
		}
		
		String strOtherResponsible = this.getParameter("strOtherResponsible", "");
		if(!strOtherResponsible.equals("")){
			page.addQueryAnd("strOtherResponsible", QueryType.markLIKE, strOtherResponsible);
		}
		
		String strPublicationDate = this.getParameter("strPublicationDate", "");
		if(!strPublicationDate.equals("")){
			page.addQueryAnd("strPublicationDate", QueryType.markLIKE, strPublicationDate);
		}

		String strSchoolId = this.getParameter("strSchoolId", "");
		if(!strSchoolId.equals("")){
			page.addQueryAnd("strSchoolId", QueryType.MarkINREVERSE, ObjUtil.strToSql(strSchoolId));
		}

		String intNumberLoans = this.getParameter("intNumberLoans", "");

		String strOrder=this.getParameter("strOrder","");
        String strSort = this.getParameter("strSort","");
        if(!"".equals(strOrder)){
            page.setSort(strSort);
            page.setOrder(strOrder);
        }
		String strOrder1 = this.getParameter("strOrder1", "");
		String strSort1 = this.getParameter("strSort1", "");
		if(!"".equals(strSort1)){
			page.setSort(strSort1);
			page.setOrder(strOrder1);
		}
		page.put("isSelCol", "true");

		String dtStartCreatDate = this.getParameter("dtStartCreatDate", "");
		if(!dtStartCreatDate.equals("")){
			page.addQueryAnd("dtCreatDate", QueryType.markGTEQ, dtStartCreatDate);
		}

		String dtEndCreatDate = this.getParameter("dtEndCreatDate", "");
		if(!dtEndCreatDate.equals("")){
			page.addQueryAnd("dtCreatDate", QueryType.markLTEQ, dtEndCreatDate);
		}

		page = libraryService.list(page);
		List<Library> libraryList = page.getDataList();
		result = this.returnPage(result, page);

		page.setUsePage(false);
		page = libraryService.list(page);
		List<Library> tempList = page.getDataList();

		Page ccpage = new Page();
		ccpage.setUsePage(false);
		ccpage.addQueryAnd("strSchoolId", "-1");
		if(libraryList!=null&& libraryList.size()>0){
			
			Map<String, Integer> countMap = new HashMap<String, Integer>();
			Map<String, List<Library>> tempMap = ObjUtil.listToMapByField(tempList, "strClassNumber");
			
                String strParentNodeId = this.getParameter("strParentNodeId", "-1");
			if(!strParentNodeId.equals("")){
				QueryField queryFiled = new QueryField();
				queryFiled.setFirstQuery("strParentNodeId", QueryType.markEQ, strParentNodeId);
				queryFiled.setSecondQuery(QueryLinkType.OR, "strId", QueryType.markEQ, strParentNodeId);
				ccpage.addQueryAnd(queryFiled);
			}
			
			ccpage.setSort("strCode");
			ccpage.setOrder("asc");
			List<ChineseClassification> list = chineseClassificationService.list(ccpage).getDataList();
			List<Map<String,Object>> childrenList = new ArrayList<Map<String,Object>>();

			for(int i =0;i<list.size();i++){
				ChineseClassification obj = list.get(i);
				String classNumber = obj.getStrCode();
				int count = 0;
				for (Map.Entry<String, List<Library>> entry : tempMap.entrySet()) {
					String tempcn = entry.getKey();
					if(tempcn.startsWith(classNumber)){
						count += entry.getValue()==null?0:entry.getValue().size();
					}
					if(countMap.get(classNumber)!=null){
						count += countMap.get(classNumber)==null?0:Integer.valueOf(countMap.get(classNumber));
					}
				}
				countMap.put(classNumber, count);
				Map<String,Object> temp = new HashMap<String,Object>();
				temp.put("strParentNodeId", obj.getStrId());
				temp.put("strParentCode", obj.getStrCode());
				temp.put("strParentNodeName", obj.getStrNodeName());
				temp.put("expand", false);
				temp.put("count", count);
				if(count>0){
					childrenList.add(temp);
				}
				
			}
			result.put("objList", childrenList);
			
		}
		
		List<Map<String,Object>> objListMap = new ArrayList<Map<String, Object>>();
		Map<String,Object> objMap = new HashMap<String, Object>();
		
		Page schoolPage = new Page();
		schoolPage.setUsePage(false);
		if(!strSchoolId.equals("")){
			schoolPage.addQueryAnd("strId", QueryType.MarkINREVERSE, ObjUtil.strToSql(strSchoolId));
		}
		List<School> schoolList = schoolService.list(schoolPage).getDataList();
//		Map<String, School> schoolMap = ObjUtil.listToObjMapByField(schoolList, "strId");
		
		Map<String, List<Library>> typeMap = new HashMap<String, List<Library>>();
		typeMap = ObjUtil.listToMapByField(tempList, "strSchoolId");
		List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		for(int i=0;i<schoolList.size();i++){
			Map<String, Object> tempMap = new HashMap<String, Object>();
			
			School school = schoolList.get(i);//schoolMap.get(entry.getKey());
			tempMap.put("item", school!=null?school.getStrName():"");
			tempMap.put("id", school.getStrId());
			tempMap.put("count", typeMap.get(school.getStrId())==null?0:typeMap.get(school.getStrId()).size());
			listMap.add(tempMap);
		}
		objMap.put("title","分馆");
		Collections.sort(listMap, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            	Integer sort1 = Integer.valueOf(o1.get("count")+"");//从list中拿出来第一个的id和name拼接到一起
            	Integer sort2 = Integer.valueOf(o2.get("count")+"");//从list中拿出来第二个的id和name拼接到一起
                return sort2.compareTo(sort1);//利用String类的compareTo方法
            }
		});
		objMap.put("list",listMap);
		objListMap.add(objMap);
		
		objMap = new HashMap<String, Object>();
		typeMap = ObjUtil.listToMapByField(tempList, "strFirstResponsible");
		listMap = new ArrayList<Map<String, Object>>();
		for (Map.Entry<String, List<Library>> entry : typeMap.entrySet()) {
			Map<String, Object> tempMap = new HashMap<String, Object>();
			
			if(entry.getKey()!=null&&entry.getValue()!=null && !entry.getKey().equals("null")&& !entry.getKey().equals("")){
				tempMap.put("item", entry.getKey()+"");
				tempMap.put("count", entry.getValue().size());
				listMap.add(tempMap);
			}
		}
		objMap.put("title","责任者");
		Collections.sort(listMap, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            	Integer sort1 = Integer.valueOf(o1.get("count")+"");//从list中拿出来第一个的id和name拼接到一起
            	Integer sort2 = Integer.valueOf(o2.get("count")+"");//从list中拿出来第二个的id和name拼接到一起
                return sort2.compareTo(sort1);//利用String类的compareTo方法
            }
		});
		objMap.put("list",listMap);
		objListMap.add(objMap);
		
		objMap = new HashMap<String, Object>();
		typeMap = ObjUtil.listToMapByField(tempList, "strPublisher");
		listMap = new ArrayList<Map<String, Object>>();
		for (Map.Entry<String, List<Library>> entry : typeMap.entrySet()) {
			Map<String, Object> tempMap = new HashMap<String, Object>();
			
			if(entry.getKey()!=null&&entry.getValue()!=null && !entry.getKey().equals("null")&& !entry.getKey().equals("")){
				tempMap.put("item", entry.getKey()+"");
				tempMap.put("count", entry.getValue().size());
				listMap.add(tempMap);
			}
		}
		objMap.put("title","出版社");
		Collections.sort(listMap, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            	Integer sort1 = Integer.valueOf(o1.get("count")+"");//从list中拿出来第一个的id和name拼接到一起
            	Integer sort2 = Integer.valueOf(o2.get("count")+"");//从list中拿出来第二个的id和name拼接到一起
                return sort2.compareTo(sort1);//利用String类的compareTo方法
            }
		});
		objMap.put("list",listMap);
		objListMap.add(objMap);
		
		objMap = new HashMap<String, Object>();
		typeMap = ObjUtil.listToMapByField(tempList, "strPublicationDate");
		listMap = new ArrayList<Map<String, Object>>();
		for (Map.Entry<String, List<Library>> entry : typeMap.entrySet()) {
			Map<String, Object> tempMap = new HashMap<String, Object>();
			
			if(entry.getKey()!=null&&entry.getValue()!=null && !entry.getKey().equals("null")&& !entry.getKey().equals("")){
				tempMap.put("item", entry.getKey()+"");
				tempMap.put("count", entry.getValue().size());
				listMap.add(tempMap);
			}
		}
		objMap.put("title","出版日期");
		Collections.sort(listMap, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            	Integer sort1 = Integer.valueOf(o1.get("count")+"");//从list中拿出来第一个的id和name拼接到一起
            	Integer sort2 = Integer.valueOf(o2.get("count")+"");//从list中拿出来第二个的id和name拼接到一起
                return sort2.compareTo(sort1);//利用String类的compareTo方法
            }
		});
		objMap.put("list",listMap);
		objListMap.add(objMap);
		
		result.put("totalList", objListMap);
		
		ResponseUtil.writeJson(result, response);

	}

    /**
     *多字段搜索
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/many")
    public void getManyLately(@RequestBody LatelyVo latelyVo, HttpServletRequest request, HttpServletResponse response) throws Exception{
		HandlerResult result = new HandlerResult();
        if(result.getCode()==0){
        	List<Library> manyLibrary= libraryService.manyLately(latelyVo);
        	result.put("manyLibrary",manyLibrary);
        }
		ResponseUtil.writeJson(result, response);
    }

	/**
	 * 全部出版社
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/presslist")
	public void getPressList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		HandlerResult result = new HandlerResult();
		List<Library> press=null;
		if(result.getCode()==0){
			press=libraryService.pressList();
		}
		result.put("press",press);
		ResponseUtil.writeJson(result, response);
	}
    /***
     * 热门图书
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/hotbooklist/{page}/{size}")
    public void hotBookList(@RequestBody(required = false) hotVo hotVoConditions,
							@PathVariable Integer page,
							@PathVariable Integer size,
							HttpServletRequest request, HttpServletResponse response) throws Exception{
        HandlerResult result = new HandlerResult();
		List<hotResult> list=null;
		int pageNum=0;
		int pages=0;
		int pageSize=0;
		long total=0;
		if(result.getCode()==0){
			PageInfo<hotResult> hotResults=libraryService.getHotBookList(hotVoConditions,page,size);
			list = hotResults.getList();
			pageNum = hotResults.getPageNum();
			pages = hotResults.getPages();
			pageSize = hotResults.getPageSize();
			total = hotResults.getTotal();
		}
		result.put("list",list);
		result.put("pageNum",pageNum);
		result.put("pages",pages);
		result.put("pageSize",pageSize);
		result.put("total",total);
		ResponseUtil.writeJson(result, response);
    }
	
	/**
	 * 列表页面数据处理，包括查询
	 * @param
	 * @param response
	 */
	@RequestMapping(value="/chineseClassificationList")
	public void chineseClassificationList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		

		Page page = this.setPage();
		
		String strParentNodeId = this.getParameter("strParentNodeId", "");
		if(!strParentNodeId.equals("")){
			page.addQueryAnd("strParentNodeId", strParentNodeId);
		}
		
		page.addQueryAnd("strSchoolId", "-1");
		page.setSort("strCode");
		page.setOrder("asc");
		
		page = chineseClassificationService.list(page);
		List<ChineseClassification> list = page.getDataList();
		
		Map<String, List<ChineseClassification>> menuMap = ObjUtil.listToMapByField(list, "strParentNodeId");
		list = creatChineseClassificationTree(list, menuMap);
		List<Map<String,Object>> objList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> childrenList = new ArrayList<Map<String,Object>>();
		
		if(list!=null && list.size()>0){
			for(ChineseClassification obj:list){
				if(obj.getStrParentNodeId().equals(strParentNodeId)){
					Map<String,Object> temp = new HashMap<String,Object>();
					temp.put("strParentNodeId", obj.getStrId());
					temp.put("strParentCode", obj.getStrCode());
					temp.put("strParentNodeName", obj.getStrNodeName());
					List<Map<String,Object>> tempJson = creatJsonTree(obj.getChildren());
					if(tempJson!=null && tempJson.size()>0){
						temp.put("children", tempJson);
					}
					temp.put("expand", false);
					childrenList.add(temp);
				}
			}
			
		}
		result.put("objList", childrenList);
			
		
		ResponseUtil.writeJson(result, response);

	}
	
	/**
	 * 列表页面数据处理，包括查询
	 * @param
	 * @param response
	 */
	@RequestMapping(value="/schoolList")
	public void schoolList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		

		Page page = this.setPage();
		page.removeQueryAnd("strSchoolId");
		page.setSort("strCode");
		page.setOrder("asc");
		page.setUsePage(false);
		page = schoolService.list(page);
		List<School> list = page.getDataList();
		result.put("objList", list);
			
		ResponseUtil.writeJson(result, response);

	}
	
	@RequestMapping(value="/getLibrary")
	public void getLibrary(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			
			String strId = this.getParameter("strId", "");
			Library obj = libraryService.findById(strId);
			
			Bookshelf bookshelf = bookshelfService.findById(obj.getStrBookshelf());
			if(bookshelf!=null){
				obj.setStrBookshelf(bookshelf.getStrBookshelfName());
			}
			
			result.put("obj", obj);
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	private List<Map<String,Object>> creatJsonTree(List<ChineseClassification> menuList){
		List<Map<String,Object>> tempList = new ArrayList<Map<String,Object>>();
		if(menuList != null){
			for(ChineseClassification obj: menuList){
				Map<String,Object> tempMap = new HashMap<String,Object>();
				
				tempMap.put("strParentNodeId", obj.getStrId());
				tempMap.put("strParentCode", obj.getStrCode());
				tempMap.put("strParentNodeName", obj.getStrNodeName());
				List<Map<String,Object>> tempJson = creatJsonTree(obj.getChildren());
				if(tempJson!=null && tempJson.size()>0){
					tempMap.put("children", tempJson);
				}
				tempMap.put("expand", false);
				tempList.add(tempMap);
			}
		}
		return tempList;
	}
	
	private List<ChineseClassification> creatChineseClassificationTree(List<ChineseClassification> menuList,Map<String, List<ChineseClassification>> menuListMap){
		List<ChineseClassification> list=null;
		for(int i=0;menuList!=null&&i<menuList.size();i++){
			ChineseClassification obj=menuList.get(i);
			list=list==null?new ArrayList<ChineseClassification>():list;
			obj.setChildren(creatChineseClassificationTree(menuListMap.get(obj.getStrId()),menuListMap));
				
			list.add(obj);
		}
		return list;
	}
}
